from flask import Blueprint, jsonify, request
from remote_ssh import Client
from loguru import logger
import flask_config


logger.add("ssh_remote_connetc.log", level="INFO", rotation="1 week", retention="10 days")
bp_mrlic = Blueprint('mrlic',__name__,url_prefix='/mrlic/')

rule_file = flask_config.RULE_FILE
mrlic_hostname = flask_config.MRLIC_SERVER
mrlic_tocken = flask_config.MRLIC_TOCKEN


@bp_mrlic.route("downloading")
def query_downloading_build():

    data ={}
    data["status"] = "idle"
    data["downloading_build"] = ""
    try:
        mrlic_server = Client(hostname=mrlic_hostname)
        cmd = "ls /opt/autodownload/ | grep downloading"
        res = mrlic_server.exec_command(cmd).strip()
        if res:
            cmd_pid = "ps -ef | grep xdownloadusb_new | grep -v grep |awk '{print $2}'"
            pid = mrlic_server.exec_command(cmd_pid)
            data["pid"] = pid

            cmd_time = f"ps -o etimes -p {pid} | tail -1"
            res_time = mrlic_server.exec_command(cmd_time)
            mins = str(int(res_time) / 60)
            seds = str(int(res_time) % 60)
            duration = mins + "分" + seds + "秒"

            data["duration"] = duration
            data["status"] = "busy"
            data["downloading_build"] = res
        return jsonify(data)
    except Exception as e:
        logger.error(e)
    finally:
        mrlic_server.close()

@bp_mrlic.route("rules")
def query_download_rules():
    data = {}
    data["rules"] = []
    try:
        mrlic_server = Client(hostname=mrlic_hostname)
        # cmd = " grep ^ls /opt/autodownload/mvxtest.BJ | awk '{print $3, $4, $12, $13}'"
        cmd = f" grep ^ls {rule_file}" + " | awk '{print $3, $4, $12, $13}'"
        res = mrlic_server.exec_command(cmd).strip().split("\n")
        data["rules"] = res
        return jsonify(data)

    except Exception as e:
        logger.error(e)
    finally:
        mrlic_server.close()

@bp_mrlic.route("builds")
def query_all_builds():
    data = {}
    data["builds"] = []
    try:
        mrlic_server = Client(hostname=mrlic_hostname)
        cmd = "find /b/pvr2 -maxdepth 1 -type d -name '*.?_*_????.*' 2>/dev/null"
        res = mrlic_server.exec_command(cmd).strip().split("\n")
        data["builds"] = [item.split('/')[-1] for item in res]
        return jsonify(data)

    except Exception as e:
        logger.error(e)
    finally:
        mrlic_server.close()

@bp_mrlic.route("nas_builds")
def query_nas_all_builds():
    data = {}
    data["builds"] = []
    try:
        mrlic_server = Client(hostname=mrlic_hostname)
        cmd = "find /b/MR_iso_prd_nas -maxdepth 1 -type d -name '*.?_*_????.*' 2>/dev/null"
        res = mrlic_server.exec_command(cmd).strip().split("\n")
        data["builds"] = [item.split('/')[-1] for item in res]
        return jsonify(data)

    except Exception as e:
        logger.error(e)
    finally:
        mrlic_server.close()

@bp_mrlic.route("insert_rule")
def insert_rule():
    tocken = request.args.get("tocken")
    rule = request.args.get("rule")
    data = {}
    data["status"] = False
    if rule and tocken == mrlic_tocken:
        data["status"] = True
        try:
            mrlic_server = Client(hostname=mrlic_hostname, username="root")
            cmd = f"""sed -i "1a ls -lrt /b/pvr2 | grep {rule.strip()} |""" + " awk '{print $NF}'" + f""" | grep ^{rule.strip()} | tail -n6" {rule_file}"""
            # logger.debug(cmd)
            res = mrlic_server.exec_command(cmd)
            data["insert"] = "ok"
            return jsonify(data)

        except Exception as e:
            logger.error(e)
        finally:
            mrlic_server.close()
    else:
        return jsonify(data)
